package com.seasonsfood.mall.service.dispatch.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.seasonsfood.mall.core.service.impl.BaseServiceImpl;
import com.seasonsfood.mall.service.dispatch.utils.ListUniqUtils;
import com.seasonsfood.mall.service.dispatch.utils.MapUtils;
import com.seasonsfood.mall.service.dispatch.api.domain.DispArea;
import com.seasonsfood.mall.service.dispatch.api.domain.DispCircuitRelevanceSite;
import com.seasonsfood.mall.service.dispatch.api.domain.DispSite;
import com.seasonsfood.mall.service.dispatch.api.model.DispSiteResp;
import com.seasonsfood.mall.service.dispatch.api.param.DispSiteRequest;
import com.seasonsfood.mall.service.dispatch.api.param.RecentCellAndSort;
import com.seasonsfood.mall.service.dispatch.api.param.StreetAndSite;
import com.seasonsfood.mall.service.dispatch.api.service.DispSiteService;
import com.seasonsfood.mall.service.dispatch.mapper.DispAreaMapper;
import com.seasonsfood.mall.service.dispatch.mapper.DispCircuitRelevanceSiteMapper;
import com.seasonsfood.mall.service.dispatch.mapper.DispSiteMapper;
import com.seasonsfood.mall.util.constant.ResponseCode;
import com.seasonsfood.mall.util.model.ListResponse;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component("dispSiteService")
@Service(interfaceClass = DispSiteService.class)
public class DispSiteServiceImpl extends BaseServiceImpl<DispSite> implements DispSiteService {


    @Resource
    DispSiteMapper dispSiteMapper;
    @Resource
    DispAreaMapper dispAreaMapper;
    @Resource
    DispCircuitRelevanceSiteMapper dispCircuitRelevanceSiteMapper;

    @Override
    public List<DispSite> getSiteListByStreetId(Long id) {
        return dispSiteMapper.getSiteListByStreetId(id);
    }

    @Override
    public ListResponse<DispSiteResp> listModelSiteList(DispSiteRequest request) {
        if (request.getSiteName() != null) {
            request.setSiteName("%" + request.getSiteName() + "%");
        }

        if (request.getDispatchName() != null) {
            request.setDispatchName("%" + request.getDispatchName() + "%");
        }
        if (request.getCircuitName() != null) {
            request.setDispatchName(null);
            request.setCircuitName("%" + request.getCircuitName() + "%");
        }
        PageHelper.startPage(request.getPage(), request.getPageSize());
        List<DispSiteResp> dispSiteList = dispSiteMapper.listModelSiteList(request);


        return new ListResponse<DispSiteResp>(new PageInfo(dispSiteList));
    }


    @Override
    public ListResponse<StreetAndSite> findSiteLocation(String siteName) {
        if (siteName != null) {
            siteName = "%" + siteName + "%";
        }
        return new ListResponse<StreetAndSite>(new PageInfo(dispSiteMapper.findSiteLocation(siteName)));
    }


    @Override
    public ResponseCode addDispSite(DispSite dispSite, List<Long> circuitIdList) {
        dispSite.setCreateTime(new Date());
        //插入地址表
        int count = dispSiteMapper.insertSelective(dispSite);
        if (count <= 0) {
            return ResponseCode.ADD_ERROR;
        }
        System.out.print("返回的id" + dispSite.getId());
        //给上级街道加一个下一级地址数
        DispArea dispArea = dispAreaMapper.selectByPrimaryKey(dispSite.getParentStreetId());
        if (dispArea == null) {
            return ResponseCode.DATA_ERROR;
        }
        DispArea dispArea2 = new DispArea();
        dispArea2.setId(dispArea.getId());
        dispArea2.setChildAreaTotalNum(dispArea.getChildAreaTotalNum() + 1);
        count = dispAreaMapper.updateByPrimaryKeySelective(dispArea2);
        if (count <= 0) {
            return ResponseCode.ADD_ERROR;
        }
        //中心仓位置.现在先写后面分仓以后再建数据库存储
        Double lat = 25.082036;
        Double lng = 117.02867;

        for (int i = 0; i < circuitIdList.size(); i++) {
            //找出一个当前线路下与添加小区最近的小区
            RecentCellAndSort recentCellAndSort = dispSiteMapper.selectSiteByLngAndLat(circuitIdList.get(i), dispSite.getLng(), dispSite.getLat());
            //添加地址与中心仓位置距离
            double distance = MapUtils.GetDistance(dispSite.getLat(), dispSite.getLng(), lat, lng);
            //查找出来的地址与中心仓位置距离
            double distance2 = MapUtils.GetDistance(recentCellAndSort.getLat(), recentCellAndSort.getLat(), lat, lng);

            if (distance >= distance2) {
                recentCellAndSort.setOrderLy(recentCellAndSort.getOrderLy() + 1);
            }
            dispCircuitRelevanceSiteMapper.updateOrderLy(circuitIdList.get(i), recentCellAndSort.getOrderLy());
            DispCircuitRelevanceSite dispCircuitRelevanceSite = new DispCircuitRelevanceSite();
            dispCircuitRelevanceSite.setCircuitId(circuitIdList.get(i));
            dispCircuitRelevanceSite.setSiteOrderly(recentCellAndSort.getOrderLy());
            dispCircuitRelevanceSite.setSiteId(dispSite.getId());
            dispCircuitRelevanceSite.setCreateTime(new Date());
            count = dispCircuitRelevanceSiteMapper.insertSelective(dispCircuitRelevanceSite);
            if (count <= 0) {
                return ResponseCode.ADD_ERROR;
            }
        }
        return ResponseCode.SUCCESS;
    }

    @Override
    public ResponseCode updateDispSite(DispSite dispSite, List<Long> circuitIdList) {
        DispSite formerDispSite = dispSiteMapper.selectByPrimaryKey(dispSite.getId());
        //如果分配的地点位于不同街道增加或减少各自上级区域注册人数
        if (formerDispSite.getParentStreetId() != dispSite.getParentStreetId() && dispSite.getParentStreetId() != null) {
            DispArea dispArea1 = dispAreaMapper.selectByPrimaryKey(formerDispSite.getParentStreetId());
            DispArea dispArea2 = dispAreaMapper.selectByPrimaryKey(dispSite.getParentStreetId());
            dispArea1.setCurrentAreaRegisterUserNum(dispArea1.getCurrentAreaRegisterUserNum() - formerDispSite.getRegisterUserNum());
            dispAreaMapper.updateByPrimaryKey(dispArea1);
            dispArea2.setCurrentAreaRegisterUserNum(dispArea2.getCurrentAreaRegisterUserNum() + formerDispSite.getRegisterUserNum());
            dispAreaMapper.updateByPrimaryKey(dispArea2);
        }
        //如果线路列表不为空要删除原来有的而现在不存在的,添加现在添加的
        if (circuitIdList.isEmpty()) {
            Example example = new Example(DispCircuitRelevanceSite.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("siteId", dispSite.getId());
            List<DispCircuitRelevanceSite> dispCircuitRelevanceSiteList= dispCircuitRelevanceSiteMapper.selectByExample(example);
            List<Long> formerList=new ArrayList<Long>();
            for (int i=0;i<dispCircuitRelevanceSiteList.size();i++){
               formerList.add(dispCircuitRelevanceSiteList.get(i).getCircuitId());
            }
            //需要删除的
            List<Long> needDelList= ListUniqUtils.needDel(formerList,circuitIdList);
            for (int i = 0; i < needDelList.size(); i++) {
                criteria.andEqualTo("circuitId",needDelList.get(i));
                dispCircuitRelevanceSiteMapper.deleteByExample(example);


            }

            Double lat = 25.082036;
            Double lng = 117.02867;
            //需要添加的
            List<Long> needAddList= ListUniqUtils.needadd(formerList,circuitIdList);
            for (int i = 0; i < needAddList.size(); i++) {
                //找出一个当前线路下与添加小区最近的小区
                RecentCellAndSort recentCellAndSort = dispSiteMapper.selectSiteByLngAndLat(needAddList.get(i), dispSite.getLng(), dispSite.getLat());
                //添加地址与中心仓位置距离
                double distance = MapUtils.GetDistance(dispSite.getLat(), dispSite.getLng(), lat, lng);
                //查找出来的地址与中心仓位置距离
                double distance2 = MapUtils.GetDistance(recentCellAndSort.getLat(), recentCellAndSort.getLat(), lat, lng);

                if (distance >= distance2) {
                    recentCellAndSort.setOrderLy(recentCellAndSort.getOrderLy() + 1);
                }
                dispCircuitRelevanceSiteMapper.updateOrderLy(needAddList.get(i), recentCellAndSort.getOrderLy());
                DispCircuitRelevanceSite dispCircuitRelevanceSite = new DispCircuitRelevanceSite();
                dispCircuitRelevanceSite.setCircuitId(needAddList.get(i));
                dispCircuitRelevanceSite.setSiteOrderly(recentCellAndSort.getOrderLy());
                dispCircuitRelevanceSite.setSiteId(dispSite.getId());
                dispCircuitRelevanceSite.setCreateTime(new Date());
                dispCircuitRelevanceSiteMapper.insertSelective(dispCircuitRelevanceSite);

            }
        }
        int count = dispSiteMapper.updateByPrimaryKeySelective(dispSite);
        if (count <= 0) {
            return ResponseCode.MODIFY_ERROR;
        }
        Example example = new Example(DispCircuitRelevanceSite.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("siteId", dispSite.getId());
        DispCircuitRelevanceSite dispCircuitRelevanceSite = new DispCircuitRelevanceSite();
        if (dispSite.getIsDel() == 1 && dispSite.getIsDel() != null) {
            dispCircuitRelevanceSite.setIsStart(0);
        } else {
            dispCircuitRelevanceSite.setIsStart(dispSite.getIsStart());
        }
        count = dispCircuitRelevanceSiteMapper.updateByExampleSelective(dispCircuitRelevanceSite, example);
        if (count <= 0) {
            return ResponseCode.MODIFY_ERROR;
        }
        return ResponseCode.SUCCESS;
    }
}
